import { Component, OnInit } from '@angular/core';
import { seriesData } from "../power-compare/compare-echarts/echarts.model";
import { ActualWindPower } from "../../../entity/actual-wind-power.model";
import { List } from 'linqts';
import { PowerLoss } from "../../..//entity/power-loss.model";
import { ActualWindPowerService } from "../../../service/actual-wind-power.service";
import { WindPowers } from "../../../entity/wind-powers.model";
import { FarmCategoryEnum } from '../../common/device-tag-selector/farm-category.enum';
import { DeviceCategoryEnum } from '../../common/device-tag-selector/device-category.enum';
import { Device } from "../../../entity/device.model";
import { NzMessageService } from 'ng-zorro-antd';
import { ApplicationService } from "../../../service/application.service";
import { PowerLossRankService } from '../../../service/power-loss-rank.service';
@Component({
	selector: 'app-power-change',
	templateUrl: './power-change.component.html',
	styleUrls: ['./power-change.component.css']
})
export class PowerChangeComponent implements OnInit {
	public farmCategory: FarmCategoryEnum = FarmCategoryEnum.winfarm;
	public deviceCategory: DeviceCategoryEnum[] = [DeviceCategoryEnum.turbine];
	//图表数据模型
	private actualWindPowerData: ActualWindPower[] = [];
	private originalActual: ActualWindPower[] = [];

	//型号设计曲线数据
	private modelWindPowerData: WindPowers[] = [];
	private originalModelWindPower: WindPowers[] = [];

	private powerLossData: PowerLoss[] = [];
	private originalPowerLoss: PowerLoss[] = [];
	public compareDataHigh: PowerLoss[] = [];
	public compareDataLow: PowerLoss[] = [];

	//EPLostPerformTotalPer > 10%(偏低), EPLostPerformTotalPer < -10%(偏高)，比较参数
	private compareParamHigh: number = -10;
	private compareParamLow: number = 10;

	public years: string[] = []
	public currentYear: string = new Date().getFullYear().toString();
	

	/**
	* 当前风场风机
	* 
	* @type {TurbData}@memberof TurbineDetailComponent
	*/
	public currentDevice: Device;
	/**
	* 是否显示风机选择组件
	* 
	* @type {boolean}@memberof TurbineDetailComponent
	*/
	public showSelector: boolean = false;

	/**
	* echart series(单个风机选择)
	* 
	* @type {any[]}@memberof TurbineTrendComponent
	*/
	monthPowerSeries: seriesData[] = [];

	/**
	* 图例
	* 
	* @type {object}@memberof TurbineTrendComponent
	*/
	monthPowerLegend: {};
	private legendNames: string[] = [];

	public maxPower: number;

	public turbineIds: number[] = [];
	private dateType: number;
	public low: boolean;
	public high: boolean;

	constructor(
		private actualWindPowerService: ActualWindPowerService,
		private _message: NzMessageService,
		private application: ApplicationService,
		private powerLossRankService: PowerLossRankService
	) { }

	ngOnInit() {
		for(let i=0;i<10;i++){
			this.years.push((Number(this.currentYear)-1+i).toString());
		}
	}

	/**
	* 滑入风机系统tab时显示对应的风机系统
	* 
	* @type {}@memberof TurbineDetailComponent
	*/
	public onMouseEnter() {
		this.showSelector = true;
	}
	/**
	* 滑出风机系统tab时隐藏对应的风机系统
	* 
	* @type {}@memberof TurbineDetailComponent
	*/
	public onMouseLeave(ev) {
		if (!ev.toElement) return false;
		this.showSelector = false;
	}

	onSelectFarmRadio(ev: Device[]) {
		this.turbineIds = [];
		this.currentDevice = ev[0];
		this.turbineIds.push(ev[0].deviceId);
		this.showSelector = false;

		this.onSearch();
	}

	public onChangeYear(event) {
		this.currentYear = event;
	}

	public onSearch() {
		this.initEchartsData();
	}

	private initEchartsData() {
		let startTime = new Date(this.currentYear);
		let endTime = new Date(this.currentYear + '-' + '12' + '-' + '31');    // 年	
		this.dateType = 2;

		if (this.turbineIds.length === 0) {
			alert('请选择风机！')
			return
		}

		this.actualWindPowerService.getWindPowerDataByTurbId(this.turbineIds, this.dateType, startTime, endTime) // this.turbineIds
			.then(res => {
				if (!res) { return false; };
				this.actualWindPowerData = [];
				this.originalActual = [];
				this.powerLossData = [];
				this.originalPowerLoss = [];
				this.compareDataHigh = [];
				this.compareDataLow = [];
				this.legendNames = [];
				this.originalModelWindPower = [];
				this.modelWindPowerData = [];
				
				this.originalActual = [...res.actualWindPowerList];
				this.actualWindPowerData.push(...this.originalActual);

				// 电量耗损数据
				this.originalPowerLoss = [...res.powerLossList];
				this.powerLossData.push(...this.originalPowerLoss);

				// 型号设计曲线数据
				this.originalModelWindPower = [...res.windPowerList];
				this.modelWindPowerData = this.originalModelWindPower;

				// 型号功率的最大值
				let powers = this.modelWindPowerData.map(o => o.power);
				this.maxPower = Math.max.apply(Math, powers) + 100;

				// 曲线通过高低分组
				this.powerLossData.forEach(o => {
					if (o.performLossPer > this.compareParamLow) {
						this.compareDataLow.push(o)
					}
					if (o.performLossPer < this.compareParamHigh) {
						this.compareDataHigh.push(o)
					}
				})

				if (this.compareDataLow.length > 0) {
					this.low = true;
				}

				if (this.compareDataHigh.length > 0) {
					this.high = true;
				}

				// 将风机按照月份分组，分为十二组加载图表；
				let list: List<ActualWindPower> = new List(this.actualWindPowerData);
				// 按状态月份分组
				let groups = list.GroupBy(grouper => grouper.date, mapper => mapper);
			
				let date = Object.getOwnPropertyNames(groups);        // ["14","15","16"]

				let series = [];
				let modelSeriesData = [];
				let actualWindPowerArr: ActualWindPower[] = [];

				this.modelWindPowerData.forEach(o => {
					modelSeriesData.push([o.wind, o.power])
				})

				series.push({
					name: '设计曲线',
					type: 'line',
					smooth: true,
					data: modelSeriesData,
				})
				this.legendNames.push('设计曲线')

				date.forEach(element => {
					actualWindPowerArr = Object.getOwnPropertyDescriptor(groups, element).value;   // 十二个数组
					let seriesData: number[][] = [];

					actualWindPowerArr.forEach(o => {
						seriesData.push([o.wind, o.power])
					})
					series.push({
						name: actualWindPowerArr[0].date,
						type: 'line',
						smooth: true,
						data: seriesData,
					})

					this.legendNames.push(actualWindPowerArr[0].date);
				})
			

				this.monthPowerSeries = series;
				this.monthPowerLegend = {
					x: 'right',
					right: '5%',
					align: 'left',
					data: this.legendNames,
					orient: 'vertical',
					y: 50,
					textStyle: {    		// 图例文字的样式
						color: '#ffa320',
						fontSize: 14
					}
				}

			})
			.catch(error => {
				if (this.application.appConfigData.isShowErr) {
					this._message.info('获取风功率数据' + error, { nzDuration: 3000 });
				}

				///console.log("app-power-change has error", error);
			});
	}

}



// WEBPACK FOOTER //
// ./src/app/module/performance/power-change/power-change.component.ts